package com.shuai.AI.ai_app.rag.config;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetriever;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetrieverOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.rag.advisor.RetrievalAugmentationAdvisor;
import org.springframework.ai.rag.generation.augmentation.ContextualQueryAugmenter;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
class CloudRetrievalAugmentationAdvisorConfig {

  @Value("${spring.ai.dashscope.api-key}")
  private String dashScopeApiKey;

  @Bean
  public Advisor cloudRetrievalAugmentationAdvisor() {
    DashScopeApi dashScopeApi = DashScopeApi.builder().apiKey(dashScopeApiKey).build();
    final String KNOWLEDGE_INDEX = "恋爱大师知识库";
    DocumentRetriever documentRetriever =
        new DashScopeDocumentRetriever(
            dashScopeApi,
            DashScopeDocumentRetrieverOptions.builder().withIndexName(KNOWLEDGE_INDEX).build());
    return RetrievalAugmentationAdvisor.builder()
        .documentRetriever(documentRetriever)
        /**
         * 如果配置为true,走的是下面的逻辑 ，当用户问题不在知识库范围内，ai会礼貌性的回复不知道， private static final PromptTemplate
         * DEFAULT_EMPTY_CONTEXT_PROMPT_TEMPLATE = new PromptTemplate(""" The user query is outside
         * your knowledge base. Politely inform the user that you can't answer it. """);
         *
         * <p>如果配置为false，或者不配置，ai只会说我不知道，走的是下面代码逻辑 private static final PromptTemplate
         * DEFAULT_PROMPT_TEMPLATE = new PromptTemplate(""" Context information is below.
         *
         * <p>--------------------- {context} ---------------------
         *
         * <p>Given the context information and no prior knowledge, answer the query.
         *
         * <p>Follow these rules:
         *
         * <p>1. If the answer is not in the context, just say that you don't know. 2. Avoid
         * statements like "Based on the context..." or "The provided information...".
         *
         * <p>Query: {query}
         *
         * <p>Answer: """);
         */
        .queryAugmenter(ContextualQueryAugmenter.builder().allowEmptyContext(true).build())
        .build();
  }
}
